package com.examination.mlib.customview.surface;

import androidx.annotation.NonNull;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.examination.mlib.R;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.yilijk.base.utils.ClickUtils;


import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import crossoverone.statuslib.StatusUtil;

@Route(path = ARouterConstants.VideoPlayerFullActivity)
public class VideoPlayerFullActivity extends ModuleBaseActivity
        implements MediaPlayer.OnCompletionListener,MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnPreparedListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnErrorListener  {
    private RelativeLayout hRlayoutVideo;
    private SurfaceView hSv;
    private ImageView hImageClickplayMoren;
    private ImageView hImageClickplay;
    private Button hBtPause;
    private TextView hTvCurrentProgress;
    private SeekBar hSeekBar;
    private TextView hTvTotalProgress;
    private Button hBtMinisize;
    private ImageView hVideoBack;

    private int screenWidth;
    private int screenHeight;

    @Autowired
    protected int currentPosition;
    @Autowired
    protected String url;

    private Timer timer;
    private TimerTask task;
    private MediaPlayer mediaPlayer;
    private static int savedPosition;
    private SurfaceHolder holder;

    @Override
    public int bondLayout() {
        return R.layout.activity_video_player_full;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void initView() {

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        StatusUtil.setSystemStatus(this,true,false);
        StatusUtil.setUseStatusBarColor(this, R.color.transparent);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth= dm.widthPixels;
        screenHeight= dm.heightPixels;

        hVideoBack = (ImageView) findViewById(R.id.h_video_back);

        hRlayoutVideo = (RelativeLayout) findViewById(R.id.h_rlayout_video);
        hSv = (SurfaceView) findViewById(R.id.h_sv);
        hImageClickplayMoren = (ImageView) findViewById(R.id.h_image_clickplay_moren);
        hImageClickplay = (ImageView) findViewById(R.id.h_image_clickplay);
        hBtPause = (Button) findViewById(R.id.h_bt_pause);
        hTvCurrentProgress = (TextView) findViewById(R.id.h_tv_currentProgress);
        hSeekBar = (SeekBar) findViewById(R.id.h_seekBar);
        hTvTotalProgress = (TextView) findViewById(R.id.h_tv_totalProgress);
        hBtMinisize = (Button) findViewById(R.id.h_bt_minisize);


        hBtMinisize.setVisibility(View.VISIBLE);



        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnVideoSizeChangedListener(this);
        savedPosition = currentPosition;
        hSv.setOnTouchListener(new OnDoubleClickListener(new OnDoubleClickListener.DoubleClickCallback() {
            @Override
            public void onDoubleClick() {
                // TODO Auto-generated method stub
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    //bt_pause.setText(STATE_CONTINUE);
                    videoPlayStateImageRefresh(true);
                    hBtPause.setBackgroundResource(R.mipmap.videoplayer_pause);
                } else {
                    mediaPlayer.start();
                    //bt_pause.setText(STATE_PAUSE);
                    videoPlayStateImageRefresh(false);
                    hBtPause.setBackgroundResource(R.mipmap.videoplayer_play);
                    return;
                }
            }
        }));

        holder = hSv.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        hSeekBar.setOnSeekBarChangeListener(this);
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if (savedPosition > 0) {//�����¼�������в��Ž��ȡ�
                    try {
                        hImageClickplayMoren.setVisibility(View.GONE);
                        hBtPause.setBackgroundResource(R.mipmap.videoplayer_play);
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(url);
                        mediaPlayer.setDisplay(holder);
                        mediaPlayer.prepareAsync();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if (mediaPlayer != null) {
                    savedPosition = mediaPlayer.getCurrentPosition();//��ǰ����λ��
                    mediaPlayer.stop();
                    timer.cancel();
                    task.cancel();
                    timer = null;
                    task = null;
                }
            }
        });

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        ClickUtils.setFastOnClickListener(hVideoBack, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("currentPosition",mediaPlayer.getCurrentPosition());
                setResult(2001,intent);
                finish();
            }
        });
        ClickUtils.setFastOnClickListener(hBtMinisize, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("currentPosition",mediaPlayer.getCurrentPosition());
                setResult(2001,intent);
                finish();
            }
        });
        ClickUtils.setFastOnClickListener(hImageClickplayMoren, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playUrl();
                hImageClickplayMoren.setVisibility(View.GONE);
                hBtPause.setBackgroundResource(R.mipmap.videoplayer_play);
            }
        });
        ClickUtils.setFastOnClickListener(hImageClickplay, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        //bt_pause.setText(STATE_CONTINUE);
                        videoPlayStateImageRefresh(true);
                        hBtPause.setBackgroundResource(R.mipmap.videoplayer_pause);
                    } else {
                        mediaPlayer.start();
                        //bt_pause.setText(STATE_PAUSE);
                        videoPlayStateImageRefresh(false);
                        hBtPause.setBackgroundResource(R.mipmap.videoplayer_play);
                        return;
                    }
                }
            }
        });
        ClickUtils.setFastOnClickListener(hBtPause, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pause();
            }
        });
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        videoPlayStateImageRefresh(true);
        hBtPause.setBackgroundResource(R.mipmap.videoplayer_pause);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();
        //=============
        mediaPlayer.seekTo(savedPosition);//开始时是从0开始播放，恢复时是从指定位置开始播放
        hSeekBar.setMax(mediaPlayer.getDuration());//将进度条的最大值设为文件的总时长
        hTvCurrentProgress.setText("00:00");
        hTvTotalProgress.setText(String.valueOf(msConvertToMinute(mediaPlayer.getDuration())));
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                hSeekBar.setProgress(mediaPlayer.getCurrentPosition());//将媒体播放器当前播放的位置赋值给进度条的进度
                //tv_currentprogress.setText("00:05");
            }
        };
        timer.schedule(task, 0, 100);//0秒后执行，每隔100ms执行一次
    }



    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        hTvCurrentProgress.setText(String.valueOf(msConvertToMinute(progress)));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(seekBar.getProgress());//停止拖拽时进度条的进度
        hTvCurrentProgress.setText(String.valueOf(msConvertToMinute(seekBar.getProgress())));
    }

    public void videoPlayStateImageRefresh(boolean b) {
        if (b) {
            hImageClickplay.setVisibility(View.VISIBLE);
        }
        else {
            hImageClickplay.setVisibility(View.GONE);
        }
    }
    public void pause() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                //bt_pause.setText(STATE_CONTINUE);
                videoPlayStateImageRefresh(true);
                hBtPause.setBackgroundResource(R.mipmap.videoplayer_pause);
            } else {
                mediaPlayer.start();
                //bt_pause.setText(STATE_PAUSE);
                videoPlayStateImageRefresh(false);
                hBtPause.setBackgroundResource(R.mipmap.videoplayer_play);
                return;
            }
        }
    }

    public void stop() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        hBtPause.setText("��ͣ");
    }
    public void replay() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            mediaPlayer.seekTo(0);
        }
        hBtPause.setText("��ͣ");
    }

    public void playUrl() {
        if (!TextUtils.isEmpty(url)) {
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.setDisplay(holder);//****************
                mediaPlayer.prepareAsync();//�첽׼��
//                Toast.makeText(, "׼���У�������Ҫ��ʱ�䡭��", 1).show();
            } catch (Exception e) {
                e.printStackTrace();
//                Toast.makeText(this, "����ʧ�ܣ������Ƿ�������Ȩ��", 0).show();
            }
        } else {
//            Toast.makeText(this, "·������Ϊ��", 0).show();
        }
    }

    public String msConvertToMinute(int ms) {
        String partA="00";
        String partB="00";
        int totalsecond=ms/1000;
        int minute=totalsecond/60;
        int second=totalsecond-minute*60;
        if (minute<10) {
            partA="0"+minute;
        }
        else {
            partA=String.valueOf(minute);
        }
        if (second<10) {
            partB="0"+second;
        }
        else {
            partB=String.valueOf(second);
        }
        return (partA+":"+partB);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent();
            intent.putExtra("currentPosition",mediaPlayer.getCurrentPosition());
            setResult(2001,intent);
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();

        int surfaceWidth = hSv.getWidth();
        int surfaceHeight = hSv.getHeight();

        //根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
        float max;
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            //竖屏模式下按视频宽度计算放大倍数值
            max = Math.max((float) videoWidth / (float) surfaceWidth, (float) videoHeight / (float) surfaceHeight);
        } else {
            //横屏模式下按视频高度计算放大倍数值
            max = Math.max(((float) videoWidth / (float) surfaceHeight), (float) videoHeight / (float) surfaceWidth);
        }

        //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
        videoWidth = (int) Math.ceil((float) videoWidth / max);
        videoHeight = (int) Math.ceil((float) videoHeight / max);

        //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(videoWidth, videoHeight);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, hRlayoutVideo.getId());
        hSv.setLayoutParams(params);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}